<template>
  <div class="diagram-merge">
    <GraphView
      :graph="graphModel"
      :isProjectMerge="true"
    />
  </div>
</template>

<script lang="ts" setup>
import { BusEvent, ProjectMergeStatus } from "@/constants/Enums";
import { EventType, GraphModel, GraphView, ShapeKey, ShapeType, MODEL_SERVER_URL, Shape } from "@/mdesign-lib/mdesign-graph.umd.js";
import { inject, onMounted, reactive, ref } from "vue";
import { GraphOption } from "../../comps/station/graphTabs/graphEditor/GraphOption";
import { modelService, projectService } from "../../service";
import { MergeModelData, Status } from "./component/logic";

const props = defineProps<{
  data: MergeModelData;
  type: string;
}>();
const emit = defineEmits<{
  (event: "open-model-merge", data: Shape): void;
}>();
const targetProjectId = inject("targetProjectId") as string;
const sourceProjectId = inject("sourceProjectId") as string;

const graphOption = new GraphOption(targetProjectId);
const graphModel = reactive(new GraphModel(graphOption)) as GraphModel;
const emitShape = ref<Shape>();
const events = createEvents();
graphModel.emitter.onBatch(events);

function createEvents() {
  const event = {
    [EventType.PROJECT_MERGE_SHAPE_CLICK]: (shape: Shape) => {
      // 只有新增，修改，删除的模型可以点击跳转
      if (!shape.projectMergeStatus || shape.projectMergeStatus === Status.UNMODIFIED || shape.projectMergeStatus === Status.MODIFIED) {
        return;
      }
      if (shape.shapeKey === ShapeKey.CompartmentProperty_Slot) {
        getSymbolShape(shape);
      } else {
        emitShape.value = shape;
      }
      if (emitShape.value?.modelId) {
        app.$bus.emit(BusEvent.PROJECT_MERGE_SELECTED, emitShape.value);
        emit("open-model-merge", emitShape.value);
      }
    }
  };
  return event;
}

function getSymbolShape(shape: Shape) {
  const parentShape = graphModel.shapeMap.get(shape.parentId!);
  if (parentShape) {
    if (parentShape?.shapeType !== ShapeType.Symbol) {
      getSymbolShape(parentShape);
    } else {
      emitShape.value = parentShape;
    }
  } else {
    return shape;
  }
}

onMounted(() => {
  projectService
    .projectMergeGetShapeDiff(targetProjectId, sourceProjectId, props.data.id, props.data.status)
    .then((res: { sourceShapes: Shape[]; targetShapes: Shape[] }) => {
      let shapes, besideShapes;
      if (props.type === "target") {
        shapes = res.targetShapes;
        besideShapes = res.sourceShapes;
      } else {
        shapes = res.sourceShapes;
        besideShapes = res.targetShapes;
      }
      let diagramStatus = ProjectMergeStatus.UNMODIFIED;
      const shapeMap = new Map<string, Shape>();
      shapes.forEach(element => {
        shapeMap.set(element.id, element);
        if (element.shapeType === ShapeType.Diagram) {
          diagramStatus = element.projectMergeStatus || ProjectMergeStatus.UNMODIFIED;
          // 处理边框情况，取最大
          if (props.data.status === Status.MODIFIED) {
            const besideDiagramShape = besideShapes.find(it => !it.parentId);
            element.bounds.width = Math.max(besideDiagramShape.bounds.width, element.bounds.width);
            element.bounds.height = Math.max(besideDiagramShape.bounds.height, element.bounds.height);
          }
        }
        if (element.icon) {
          if (!element.icon.startsWith("statics/") && !element.icon.startsWith(MODEL_SERVER_URL)) {
            if (element.showAttribute) element.showAttribute.location = modelService.getModelIcon(element.projectId, element.icon);
          }
        }
      });
      shapes.forEach((shape: Shape) => {
        graphModel.addShape(shape);
        if (!shape.projectMergeStatus) {
          return;
        }
        const parent = shape.parentId ? shapeMap.get(shape.parentId) : null;
        switch (shape.projectMergeStatus) {
          case ProjectMergeStatus.ADDED:
            // 如果父子都是新增的，只用标绿父
            if (parent && parent.projectMergeStatus !== ProjectMergeStatus.ADDED) {
              graphModel.markerModel.createMarker(shape, "green");
              if (props.type === "target") {
                shape.style.hidden = true;
              }
            } else if (diagramStatus === ProjectMergeStatus.ADDED) {
              if (shape.shapeType === ShapeType.Symbol || shape.shapeType === ShapeType.Edge || shape.shapeType === ShapeType.Diagram) {
                graphModel.markerModel.createMarker(shape, "green");
                if (props.type === "target") {
                  shape.style.hidden = true;
                }
              }
            }
            break;
          case ProjectMergeStatus.DELETED:
            if (parent && parent.projectMergeStatus !== ProjectMergeStatus.DELETED) {
              graphModel.markerModel.createMarker(shape, "red");
              // 对于删除的页面不展示内容，只展示红框
              if (props.type === "source") {
                shape.style.hidden = true;
              }
            } else if (diagramStatus === ProjectMergeStatus.DELETED) {
              if (shape.shapeType === ShapeType.Symbol || shape.shapeType === ShapeType.Edge || shape.shapeType === ShapeType.Diagram) {
                graphModel.markerModel.createMarker(shape, "red");
                if (props.type === "source") {
                  shape.style.hidden = true;
                }
              }
            }
            break;
          case ProjectMergeStatus.MODIFIED:
            if (!parent || !parent.parentId || parent.projectMergeStatus !== ProjectMergeStatus.MODIFIED) {
              graphModel.markerModel.createMarker(shape, "blue");
            }
            break;
          default:
            break;
        }
      });
      graphModel.sortShapes();
      graphModel.linePool.fresh();
      graphModel.viewModel.updateTranslate();
      graphModel.setDisabled(true);
    });
});
</script>

<style lang="scss" scoped>
.diagram-merge {
  height: 100%;
  overflow: hidden;
}
</style>
